package cn.itrip.trade.service;

import cn.itrip.beans.pojo.ItripHotelOrder;
import cn.itrip.beans.pojo.ItripTradeEnds;
import cn.itrip.beans.vo.SystemConfig;
import cn.itrip.dao.ItripHotelOrderMapper;
import cn.itrip.dao.ItripTradeEndsMapper;
import cn.itrip.utlis.Constants;
import com.github.wxpay.sdk.MyConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Description :
 * Created by Li on 2021-01-04 14:08:18
 */
@Slf4j
@Service
public class OrderService {
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private ItripHotelOrderMapper itripHotelOrderMapper;
    @Autowired
    private ItripTradeEndsMapper itripTradeEndsMapper;
    public boolean isProcessed(String orderNo, String tradeNo) {
        ItripHotelOrder order = itripHotelOrderMapper.selectByOrderNo(orderNo);
        return order.getOrderNo() != null && order.getOrderStatus().equals(Constants.ORDER_STATUS_WAIT_PAY);
    }

    public void paySuccess(String orderNo, String tradeNo) {
        ItripHotelOrder order = itripHotelOrderMapper.selectByOrderNo(orderNo);
        order.setTradeNo(tradeNo);
        order.setOrderStatus(Constants.ORDER_STATUS_PAY_SUCCESS);
        itripHotelOrderMapper.updatePaySuccess(order);

        ItripTradeEnds record = new ItripTradeEnds();
        record.setId(order.getId());
        record.setFlag(0);
        record.setOrderNo(orderNo);
        itripTradeEndsMapper.insert(record);
        sendGet();
    }

    private void sendGet() {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(systemConfig.getTradeEndsUrl());
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
            String result = EntityUtils.toString(response.getEntity());
            log.info(result);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try { response.close();} catch (IOException e) {}
            try { httpclient.close(); } catch (IOException e) {}
        }
    }

    public ItripHotelOrder findByOrderNo(String orderNo) {
        return itripHotelOrderMapper.selectByOrderNo(orderNo);
    }
}
